﻿<?
//xna functions
$rss_lang=array("gbk"=>"gbk","big5"=>"big5",'english'=>'english','utf8'=>"utf8");
$rss_feq = array("5","10","15","20","30","60","120");
$rss_cate  = array("1"=>"General","2"=>"Personal","3"=>"Design","4"=>"Paint","5"=>"UI","6"=>"Music","7"=>"Flash","8"=>"Web","9"=>"Site");
$rss_limit = "10";
function msubstr($str, $start, $len)
{
	$str=trim($str);
	$strlen = $start + $len;
	for($z = $start;$z < $strlen;$z++) {
		if (ord(substr($str, $z, 1)) > 0xa0) {
			$tmpstr .= substr($str, $z, 2);
			$z++;
		} else
		$tmpstr .= substr($str, $z, 1);
	}
	return $tmpstr;
} 

function doAdd(){
	global $rss_lang,$rss_feq,$rss_cate,$smarty;
	include _ROOT."/class/smarty.php";
	$smarty->assign("rss_lang",$rss_lang);
	$smarty->assign("rss_feq",$rss_feq);
	$smarty->assign("rss_cate",$rss_cate);
	$smarty->display("template/admin/add_site.tpl");
}

function doSave(){
	global $PlusDB;
	$record["title"] = $_POST["title"];
	$record["site_url"] = $_POST["site_url"];
	$record["rss_url"] = $_POST["rss_url"];
	$record["icon"] = $_POST["icon"];
	$record["rss_language"] = $_POST["rss_language"];
	$record["rss_feq"] = $_POST["rss_feq"];
	$record["rss_cate"]	=	$_POST["rss_cate"];
	$record["ctime"]	=	date("Y-m-d H:i:s");

	$xnadb = $PlusDB->prefix("xna");
	$ok=$PlusDB->autoexecute($xnadb,$record,"INSERT");
	if($ok){
		echo "添加完成";
		echo "<br>";
		echo "<a href=admin.php?module=xna>点击返回</a>";
		}else{
			echo "无法添加";
			echo "<br>";
			echo $PlusDB->errorMsg();
			echo "<br>";
			echo "<input type=\"button\" value=\"   返 回   \" onclick=\"history.go(-1)\" class=\"btn\">\n";
		}

	}

	function doList(){
		global $PlusDB,$rss_cate,$smarty;
		$start = $_GET["start"];
		$start = empty($start)?0:$start;
		$xnadb = $PlusDB->prefix("xna");
		$xnanewsdb = $PlusDB->prefix("xna_news");
		$sql	=	"select count(*) as sum ,site_id from $xnanewsdb group by site_id ";
		$rt		=  $PlusDB->execute($sql);
		while($row = $rt->fetchRow()){
			$xnum[$row[site_id]] = $row[sum];
		}
		$sql="select * from $xnadb order by ctime desc ";
		$rt = $PlusDB->execute($sql);
		$num =  $rt->recordcount();
		$num = $PlusDB->getone($sql);
		$start = ($start>$num)?0:$start;
		$page = 20;
		include _ROOT."/class/page.inc.php";
		$rt = $PlusDB->SelectLimit($sql,$page,$start);
		while($row = $rt->fetchRow()){
			$row["rss_cate"] = $rss_cate[$row["rss_cate"]];
			$row[sum] = $xnum[$row[id]];
			$ret[]=$row;
		}
		$vr = array("module"=>"xna");
		$smarty->assign("list",$ret);
		$smarty->assign("page",$page_break);
		$smarty->display("template/admin/list_site.tpl");

	}

	function doFetch($id=""){
		global $PlusDB,$defaultoutput,$rss_limit;
		$xnadb = $PlusDB->prefix("xna");
		$xnanewsdb = $PlusDB->prefix("xna_news");
		//
		$siteid= $id==""?$_GET[id]:$id;
		//
		$sql="update $xnadb set utime=now() where id='$siteid'";
		$PlusDB->execute($sql);
		//
		$sql="select * from $xnadb where id='$siteid'";
		//echo $sql;
		$siterow = $PlusDB->getrow($sql);
		$cid = $siterow["rss_cate"];
		//
		include_once(_ROOT."/class/rss.class.php");
		$rss = new lastRSS; 

		$rss->cache_dir = _ROOT.'/cache'; 
		$rss->cache_time = $siterow["rss_feq"]*60; // one hour
		$rss->CDATA = "strip";
		//$rss->cache_time = 0; // one hour

		if ($rs = $rss->get($siterow["rss_url"])) {
			
		}
		else {
			echo ('Error: RSS file not found...');
			return FALSE;
		}
		include_once(_ROOT."/class/ChangeCode.inc.php");
		$cnum=$sum=0;
		$rss_encoding = trim($rs["encoding"])>"" ? strtolower($rs["encoding"]) : $siterow["rss_language"] ;
		$items = $rs["items"];
		$num  = $rs["items_count"];
		if($num==0){
			echo "没有可用信息";
			return FALSE;
		}
		$ccnum=0;
		foreach($items as $key=>$val){
			if($ccnum>$rss_limit) continue;
			$ccnum++;
			$val[news_url]	 =		$val["link"];
			$val[news_url_sum]	=	md5($val[news_url]);
			$val[site_id]				=	$siterow[id];
			$val[site_name]		=	$siterow[title];
			$val[ctime]				=	$val[pubDate]			=	date("Y-m-d H:i:s",strtotime($val[pubDate]));
			$sql="select count(*) from $xnanewsdb where news_url_sum = '$val[news_url_sum]' ";
			$cnum = $PlusDB->getone($sql);
			if($cnum>0) continue;
			//trace($rss_encoding);
			switch($rss_encoding){
				case "gbk":
				//case "GB2312":
					$val[news_title]	=c_iconv("GBK","UTF8",$val["title"]);
					$val[news_description]	=c_iconv("GBK","UTF8",$val["description"]);
					if($val[author]) $val[author]	=c_iconv("GBK","UTF8",$val[author]);
				break;
				case "gb2312":
				//case "GB2312":
					$val[news_title]	=c_iconv("GB2312","UTF8",$val["title"]);
					$val[news_description]	=c_iconv("GB2312","UTF8",$val["description"]);
					if($val[author]) $val[author]	=c_iconv("GB2312","UTF8",$val[author]);
				break;
				case "utf8":
				case "utf-8":
				$val[news_description]	=$val["description"];
				$val[news_title]		=$val["title"];
				if($val[author]) $val[author]	=$val[author];
				break;
				case "big5":
				$val[news_description]	=c_iconv("BIG5","UTF8",$val["description"]);
				$val[news_title]			=c_iconv("BIG5","UTF8",$val["title"]);
				if($val[author]) $val[author]				=c_iconv("BIG5","UTF8",$val[author]);
				break;
				default:
					$val[news_title]			=$val["title"];
					$val[news_description]	=$val["description"];
			}//end switch
			//unset($val["pubDate"],$val["title"],$val["link"],$val["description"],$val["guid"]);
			$record["news_title"] = clearHtml($val["news_title"]);
			$record["news_description"] = clearHtml($val["news_description"]);
			$record["ctime"] = $val["ctime"];
			$record["news_url"] = $val["news_url"];
			$record["news_url_sum"]	=	$val["news_url_sum"];
			$record["site_id"]				=	$val["site_id"];
			$record["site_name"]		=	$val["site_name"];
			$record["author"]		=	$val["author"];
			//trace($record);
			if($cnum==0){
				$PlusDB->autoexecute($xnanewsdb,$record,"INSERT");
				//trace($PlusDB->errorMsg());
				echo $PlusDB->errorMsg();
				$sum=$sum+1;
			}
		}//end for
		$PlusDB->execute($sql);
		outRss($cid);
		outAtom($cid);
		outjs($cid);
		outopml();
		echo "完成 ".$sum." 入库完成!";
	}

	function doEdit(){
		global $PlusDB,$rss_feq,$rss_cate,$rss_lang,$smarty;
		$id = $_GET[id];
		if(!is_numeric($id)){
			echo "错误的ID";
			return FALSE;
		}
		$xnadb = $PlusDB->prefix("xna");
		$xnanewsdb = $PlusDB->prefix("xna_news");
		$sql="select * from $xnadb where id='$id'";
		$rt = $PlusDB->execute($sql);
		if(!$rt){
			echo "错误的ID";
			return FALSE;
		}
		$row = $rt->fetchRow();
		include _ROOT."/Class/smarty.php";
		$smarty->assign("site",$row);
		$smarty->assign("rss_lang",$rss_lang);
		$smarty->assign("rss_feq",$rss_feq);
		$smarty->assign("rss_cate",$rss_cate);
		$smarty->display("template/admin/edit_site.tpl");
	}

	function doUpdate(){
		global $PlusDB;
		$id = $_POST["id"];
		if(!is_numeric($id)){
			echo "错误的ID";
			return FALSE;
		}
		$record["title"] = $_POST["title"];
		$record["site_url"] = $_POST["site_url"];
		$record["rss_url"] = $_POST["rss_url"];
		$record["icon"] = $_POST["icon"];
		$record["rss_language"] = $_POST["rss_language"];
		$record["rss_feq"] = $_POST["rss_feq"];
		$record["rss_cate"]	=	$_POST["rss_cate"];

		$xnadb = $PlusDB->prefix("xna");
		$ok=$PlusDB->autoexecute($xnadb,$record,"UPDATE" , " id='$id' ");
		if($ok){
			echo "更新完成";
			echo "<br>";
			echo "<a href=?module=xna>点击返回</a>";
			}else{
				echo "无法更新";
				echo "<br>";
				echo $PlusDB->errorMsg();
				echo "<br>";
				echo "<input type=\"button\" value=\"   返 回   \" onclick=\"history.go(-1)\" class=\"btn\">\n";
			}
		}

		function doDelete(){
			global $PlusDB;
			$id = $_GET["id"];
			if(!is_numeric($id)){
				echo "错误的ID";
				return FALSE;
			}
			$xnadb = $PlusDB->prefix("xna");
			$xnanewsdb = $PlusDB->prefix("xna_news");
			$sql="delete from $xnanewsdb where site_id='$id' ";
			$ok = $PlusDB->execute($sql);
			if(!$ok){
				echo $PlusDB->errorMsg();
				echo "<a href=?module=xna>点击返回</a>";
				return FALSE;
			}
			$sql="delete from $xnadb where id='$id' ";
			$ok=$PlusDB->execute($sql);
			if(!$ok){
				echo $PlusDB->errorMsg();
				echo "<a href=?module=xna>点击返回</a>";
				return FALSE;
			}
			echo "删除完成<br>";
			echo "<a href=?module=xna>点击返回</a>";
		}
		
		function doClear(){
			global $PlusDB;
			$id = $_GET["id"];
			if(!is_numeric($id)){
				echo "错误的ID";
				return FALSE;
			}
			$xnadb = $PlusDB->prefix("xna");
			$xnanewsdb = $PlusDB->prefix("xna_news");
			$sql="delete from $xnanewsdb where site_id='$id' ";
			//echo "$sql";
			$ok = $PlusDB->execute($sql);
			if(!$ok){
				echo $PlusDB->errorMsg();
				echo "<a href=?module=xna>点击返回</a>";
				return FALSE;
			}
			echo "清空完成<br>";
			echo "<a href=?module=xna>点击返回</a>";
		}		

		function c_iconv($s_code,$t_code ,$str){
			if(function_exists("iconv")){
				$s_code = str_replace("UTF8","UTF-8",$s_code);
				$t_code = str_replace("UTF8","UTF-8",$t_code);
				$str = iconv($s_code,$t_code,$str);
				if($s_code=="UTF-8") $str= unescape($str);
			}else{
				$conv = new ChangeCode($s_code,$t_code);
				$str	=$conv-> ConvertIt($str);
			}
			Return  $str ;
		}

		function outRss($id){
			global $PlusDB,$rss_cate,$smarty;
			$xnadb = $PlusDB->prefix("xna");
			$xnanewsdb = $PlusDB->prefix("xna_news");
			if($id==0){
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)   order by n.ctime desc";
			}else{
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)  where a.rss_cate='$id' order by n.ctime desc";
			}
			$rt = $PlusDB->selectLimit($sql,50,0);
			while($row = $rt->fetchRow()){
				$row[news_title] = htmlspecialchars($row[news_title]);
				$row[news_description] =htmlspecialchars($row[news_description]);
				$row[news_url] =htmlspecialchars($row[news_url]);
				$row[author] =htmlspecialchars($row[author]);				
				$row[site_name] =htmlspecialchars($row[site_name]);

				$row[category]=$rss_cate[$row[rss_cate]];
				$ret[]=$row;
			}
			include _ROOT."/Class/smarty.php";
			$smarty->assign("list",$ret);
			$content  = $smarty->fetch("template/rss.tpl");
			$fp = fopen(_ROOT."/xml/rss_".$id.".xml",w);
			fputs($fp,$content);
			fclose($fp);
			if($id>0) outRss(0);
		}
		
		function outAtom($id){
			global $PlusDB,$rss_cate,$smarty;
			$xnadb = $PlusDB->prefix("xna");
			$xnanewsdb = $PlusDB->prefix("xna_news");
			if($id==0){
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)   order by n.ctime desc";
			}else{
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)  where a.rss_cate='$id' order by n.ctime desc";
			}
			$rt = $PlusDB->selectLimit($sql,50,0);
			while($row = $rt->fetchRow()){
				$row[news_title] =htmlspecialchars($row[news_title]);				
				$row[news_description] =htmlspecialchars($row[news_description]);
				$row[news_url] =htmlspecialchars($row[news_url]);
				$row[author] =htmlspecialchars($row[author]);	

				$ret[]=$row;
			}
			include _ROOT."/Class/smarty.php";
			$smarty->assign("list",$ret);
			$contentatom  = $smarty->fetch("template/atom.tpl");
			$fpatom = fopen(_ROOT."/xml/atom_".$id.".xml",w);;
			fputs($fpatom,$contentatom);
			fclose($fpatom);
			if($id>0) outAtom(0);
		}

		function outjs($id){
			global $PlusDB,$rss_cate,$smarty;
			$xnadb = $PlusDB->prefix("xna");
			$xnanewsdb = $PlusDB->prefix("xna_news");
			if($id==0){
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)   order by n.ctime desc";
			}else{
			$sql="select * ,n.ctime as ctime from $xnanewsdb n left join $xnadb a on (a.id = n.site_id)  where a.rss_cate='$id' order by n.ctime desc";
			}
			$rt = $PlusDB->selectLimit($sql,10,0);
			while($row = $rt->fetchRow()){
				$row[news_title] = htmlspecialchars($row[news_title]);
				$row[news_url] = htmlspecialchars($row[news_url]);

				$ret[]=$row;
			}
			include _ROOT."/Class/smarty.php";
			$smarty->assign("list",$ret);
			$content  = $smarty->fetch("template/js.tpl");
			$fp = fopen(_ROOT."/xml/js_".$id.".js",w);
			fputs($fp,$content);
			fclose($fp);
			if($id>0) outjs(0);
		}

		function outopml(){
			global $PlusDB,$rss_cate,$smarty;
			$xnadb = $PlusDB->prefix("xna");
			$sql="select * from $xnadb";
			$rt = $PlusDB->selectLimit($sql,10000,0);
			while($row = $rt->fetchRow()){
				$row[title] = htmlspecialchars($row[title]);
				$row[site_url] =htmlspecialchars($row[site_url]);
				$row[rss_url] =htmlspecialchars($row[rss_url]);				
				$row[site_name] =htmlspecialchars($row[site_name]);
				$row[utime] = htmlspecialchars($row[utime]);
				$ret[]=$row;
			}
			include _ROOT."/Class/smarty.php";
			$smarty->assign("list",$ret);
			$content  = $smarty->fetch("template/opml.tpl");
			$fp = fopen(_ROOT."/xml/opml.xml",w);
			fputs($fp,$content);
			fclose($fp);
			if($id>0) outopml(0);
		}

function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  $ar = $r[0];
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u")
      $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4)));
    elseif(substr($v,0,3) == "&#x")
      $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1)));
    elseif(substr($v,0,2) == "&#") {
      $ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1)));
    }
  }
  return join("",$ar);
}

function clearHtml($str){
	$str = str_replace(array("&lt;","&gt;"),array("<",">"),$str);
	$s_a=array("|<img([^>]*)>|is","|<br([^>]*)>|is","|<img([^>]*)>|is","|<br([^/>]*)>|is","|<img([^>]*)>|is","|</p([^>]*)>|is","|<a([^>]*)>|is","|<\/a>|is", "#<script.*</script>#isU","|<style.*</style>|isU");
	$r_a =array("###start###img \\1 ###end###","###start###br /###end###","###start###a \\1 ###end###","###start###/a###end###","","");
	$str = preg_replace($s_a,$r_a,$str);
	$patt = "/\<[^\>]+\>/";
	$str = preg_replace($patt, "", $str);
	$str = str_replace("###start###","<",$str);
	$str = str_replace("###end###",">",$str);
	return trim($str);
}

function getRSSLocation($html, $location){
/*
	getRSSLocation() was found at 
	http://keithdevens.com/weblog/archive/2002/Jun/03/RSSAuto-DiscoveryPHP
*/
    if(!$html or !$location){
        return false;
    }else{
        #search through the HTML, save all <link> tags
        # and store each link's attributes in an associative array
        preg_match_all('/<link\s+(.*?)\s*\/?>/si', $html, $matches);
        $links = $matches[1];
        $final_links = array();
        $link_count = count($links);
        for($n=0; $n<$link_count; $n++){
            $attributes = preg_split('/\s+/s', $links[$n]);
            foreach($attributes as $attribute){
                $att = preg_split('/\s*=\s*/s', $attribute, 2);
                if(isset($att[1])){
                    $att[1] = preg_replace('/([\'"]?)(.*)\1/', '$2', $att[1]);
                    $final_link[strtolower($att[0])] = $att[1];
                }
            }
            $final_links[$n] = $final_link;
        }
        #now figure out which one points to the RSS file
        for($n=0; $n<$link_count; $n++){
            if(strtolower($final_links[$n]['rel']) == 'alternate'){
                if(strtolower($final_links[$n]['type']) == 'application/rss+xml'){
                    $href = $final_links[$n]['href'];
                }
                if(!$href and strtolower($final_links[$n]['type']) == 'text/xml'){
                    #kludge to make the first version of this still work
                    $href = $final_links[$n]['href'];
                }
                if(!$href and strtolower($final_links[$n]['type']) == 'application/atom+xml'){
                    #kludge to make the first version of this still work
                    $href = $final_links[$n]['href'];
                }
                if($href){
                    if(strstr($href, "http://") !== false){ #if it's absolute
                        $full_url = $href;
                    }else{ #otherwise, 'absolutize' it
                        $url_parts = parse_url($location);
		// echo "<pre>" ; print_r($url_parts) ; echo "</pre>" ;
                        #only made it work for http:// links. Any problem with this?
                        $full_url = "http://$url_parts[host]";
                        if(isset($url_parts['port'])){
                            $full_url .= ":$url_parts[port]";
                        }
                        if($href{0} != '/'){ #it's a relative link on the domain
                               if (substr($url_parts['path'],-1)!='/') {
                                        $full_url .= dirname($url_parts['path']);
                                } else {
                                        $full_url .= $url_parts['path'] ;
                                }
                        }
                        $full_url .= $href;
                    }
                    return $full_url;
                }
            }
        }
        return false;
    }
}

function getFaviconURL($location){
    if(!$location){
        return false;
    }else{
	$url_parts = parse_url($location);
	$full_url = "http://$url_parts[host]";
	if(isset($url_parts['port'])){
		$full_url .= ":$url_parts[port]";
	}
	$favicon_url = $full_url . "/favicon.ico" ;
    }
    return $favicon_url;
}

function channelFavicon($location) {
	global $empty_ico_data ;
	$ico_url = getFaviconURL($location) ;
	if(!$ico_url) {
		return false ;
	}
	$cached_ico = './cache/icon/' . md5($ico_url) . ".ico" ;
    	// echo "<br> $ico_url , $cached_ico " ;
	// Serve from the cache if it is younger than $cachetime
	if (file_exists($cached_ico) && (time() - $cachetime < filemtime($cached_ico))) return $cached_ico ;
	if (!$data = @file_get_contents($ico_url)) $data=$empty_ico_data ;
	if (stristr($data,'html')) $data=$empty_ico_data ;
	$fp = fopen($cached_ico,'w') ;
	fputs($fp,$data) ;
	fclose($fp) ;
	return $cached_ico ;
}
?